
<script setup lang="ts">
import { Table } from '@/components/Table'
import { Search } from '@/components/Search'
import { useI18n } from '@/hooks/web/useI18n'
import { ContentWrap } from '@/components/ContentWrap'
import {unref, h ,reactive, ref, watch} from 'vue'
import { useTable } from '@/hooks/web/useTable'
import {ElIcon,ElTag,ElSwitch, ElRow, ElCol, ElCard, ElSkeleton, ElTreeV2, ElButton,ElImage, formatter,ElMessage } from 'element-plus'
import { useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { TableColumn } from 'element-plus/es/components/table/src/table-column/defaults'
import { Dialog } from '@/components/Dialog'
import { Descriptions } from '@/components/Descriptions'
import { spawn } from 'child_process'
import { type } from 'os'
import { useRouter } from 'vue-router'
import Detail from './components/Detail.vue'
import Write from './components/Write.vue'
import { getCouponTable,DelCoupon,AddCoupon,changeOnline} from '@/api/Coupon'
import formatDate from '@/utils/Time'
const { push } = useRouter()
const { t } = useI18n()

const columns = reactive([
  {
    field: 'coupon_name',
    label: '优惠券名称',
     search: {
      show: true,
    },
    form:{
       colProps:{
        span:13
      },
    },
    detail: {
      show:true
    }
  },
  {
    field:'couponType',
    label:'优惠券类型',
    table:{
      show:false
    },
    detail: {
      show:false
    },
    form:{
      component:'RadioButton',
      componentProps: {
      options: [
        {
          label: '满减券',
          value: '1'
        },
        {
          label: '优惠券',
          value: '2'
        }
      ]
    }
    }
  },
  {
    field:'couponPrice',
    label:'优惠券金额',
    table:{
      show:false
    },
    detail: {
      show:false
    },
    form:{
      component:'Input',
      colProps:{
        span:13
      },
    }
  },
  {
    field: 'start_date',
    label: '开始时间',
    formatter: (_: Recordable, __: TableColumn, cellValue: string) => {
      return formatDate(cellValue,'yyyy-MM-dd')
    },
    form:{
      component:'DatePicker',
      componentProps:{
        type:'date'
      },
      colProps:{
        span:24
      },
    },
    detail: {
      show:true
    }
  },
  {
    field: 'end_date',
    label: '结束时间',
     formatter: (_: Recordable, __: TableColumn, cellValue: string) => {
      return formatDate(cellValue,'yyyy-MM-dd')
    },
    form: {
      component:'DatePicker',
      componentProps:{
        type:'date'
      },
      colProps: {
        span: 24
      }
    },
    detail: {
      show:true
    }
  },
  {
    field: 'online',
    label: '上架/下架',
    search:{
      show:true,
      component:'Select',
      componentProps:{
        options: [
          {
            label: '上架',
            value: 2,
            
          },
          {
            label: '下架',
            value: 3
          },
        ]
      }
    },
    form:{
      component:'RadioButton',
      componentProps: {
      options: [
        {
          label: '上架',
          value: '2'
        },
        {
          label: '下架',
          value: '3'
        }
      ]
    }
    }, 
    detail: {
      show:true
    }
  },
  {
    field: 'mode',
    label: '发放方式',
     search: {
      show: true,
      component:'Select',
      componentProps:{
          options: [
          {
            label: '自动发放',
            value: 2
          },
          {
            label: '活动领取',
            value: 3
          },
          {
            label: '人工发放',
            value: 4
          },
          {
            label: '无限制',
            value: 5
          }
        ],
        
        }
    },
    formatter: (_: Recordable, __: TableColumn, cellValue: number) => {
        if(cellValue===2){
          return '自动发放'
        }
        if(cellValue===3){
          return '活动领取'
        }
        if(cellValue===4){
          return '人工发放' 
        }
        if(cellValue===5){
          return '无限制'
        }
        
    },
    form:{
      colProps:{
        span:24
      },
      component:'Select',
      componentProps:{
        options:[
          {
            label:'自动发放',
            value:2
          },
          {
            label:'活动领取',
            value:3
          },
          {
            label:'人工发放',
            value:4
          },
          {
            label:'无限制',
            value:5
          },
        ]
      }
    },
    detail: {
      show:true,
      
    }
  },
  {
    field:'type',
    label:'优惠券类型',
    table:{
      show:false
    },
    detail:{
      show:false
    },
    form:{
      colProps:{
        span:24
      },
      component:'Select',
      componentProps:{
        options:[
          {
            label:'商品',
            value:2
          },
          {
            label:'视频',
            value:3
          },
          {
            label:'无限制',
            value:4
          },
        ]
      }
    }
  },
  {
    field: 'issue_quantity',
    label: '发行数',
    form: {
     colProps:{
        span:13
      },
    },
    detail: {
      show:true
    }
  },
  {
    field: 'surplus',
    label: '剩余数',
    form: {
      show:false
    },
    detail: {
      show:false
    }
  },
  {
    field: 'remark',
    label: '备注',
    form: {
     colProps:{
        span:13
      },
    component: 'Input',
    componentProps: {
      type: 'textarea',
      rows: 1
    }
    },
    table:{
      show:false
    },
    detail: {
      show:true
    }
  },
  {
    field: 'action',
    width: '260px',
    label: t('tableDemo.action'),
    form: {
      colProps: {
        span: 24
      },
      show: false
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(columns)
const { register, tableObject, methods } = useTable({
  getListApi: getCouponTable,
})
const { getList,setSearchParams } = methods
getList()

const actionType=ref('')
const dilogTitle=ref('')
const CouponDialog=ref(false)
const action=(row,type)=>{
  actionType.value=type === 'detail' ? 'detail' : 'add'
  dilogTitle.value= type =='detail'?'查看详细信息':'添加优惠券'
  tableObject.currentRow=row
  CouponDialog.value=true
}
//删除
const delCouponTable=async (row)=>{
 const res = await DelCoupon({'couponId':row.coupon_id})
 getList()
}

//添加优惠券
const writeRef = ref<ComponentRef<typeof Write>>()
const addCoupon=async ()=>{
 const write = unref(writeRef)
 await write.elFormRef.validate(async (isValid) => {
    if (isValid) {
      const data = await write?.getFormData()
      console.log(data)
      const code = ref(parseInt((Math.random() + 1) * Math.pow(10,10-1)))
      console.log(code)
      const res = await AddCoupon({
        couponType:data.couponTye,
        couponName:data.coupon_name,
        endDate:formatDate(data.end_date,'yyyy-MM-dd'),
        issueQuantity:data.issue_quantity,
        mode:data.mode,
        online:data.online,
        remake:data.remake,
        startDate:formatDate(data.start_date,'yyyy-MM-dd'),
        type:data.type,
        couponPrice:data.couponPrice
        })
      if(res!=0){
        ElMessage.success({
          message:'添加成功'
        })
      }else{
        ElMessage.error({
          message:'添加失败,请重试'
        })
      }
      getList()
      CouponDialog.value=false
    }
  })
  }
  //修改状态
const changeCouponOnline=async (row)=>{
  let online=row.online==2?2:3
 const res =await changeOnline({online:row.online,coupon_id:row.coupon_id})
  if(res.data==1){
    ElMessage.success({
      message:'修改成功',
    })
  }else{
     ElMessage.error('修改失败')
  }
}
</script>

<template>
<ContentWrap title="">
    <Search
      :schema="allSchemas.searchSchema"
      @search="setSearchParams"
      @reset="setSearchParams"
    />
    <div class="mb-10px">
      <ElButton type="primary" @click="action(null,'add')">添加</ElButton>
    </div>
     <Table
          v-model:pageSize="tableObject.pageSize"
          v-model:currentPage="tableObject.currentPage"
          :loading="tableObject.loading"
          :columns="allSchemas.tableColumns"
          :data=" 
            tableObject.tableList.slice((tableObject.currentPage - 1) * tableObject.pageSize,tableObject.currentPage * tableObject.pageSize)"
          :pagination="{
            total: tableObject.total
          }"
          @register="register">
          <template #online="{ row }">
                <ElSwitch
                    v-model="row.online"
                    :active-value="2"
                    :inactive-value="3"
                    @change="changeCouponOnline(row)"
                    active-text="上架"
                    inactive-text="下架"
                    style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"

                  />
          </template>
          <template #action="{ row }">
            <ElButton type="primary" @click="action(row,'detail')">查看</ElButton>
            <ElButton type="danger"  @click="delCouponTable(row)">删除</ElButton>
         </template>
        </Table>
        <Dialog v-model="CouponDialog" :title="dilogTitle">
          <Write
            v-if="actionType !== 'detail'"
            ref="writeRef"
            :form-schema="allSchemas.formSchema"
            :current-row="tableObject.currentRow"
          />

          <Detail
            v-if="actionType === 'detail'"
            :detail-schema="allSchemas.detailSchema"
            :current-row="tableObject.currentRow"
          />

        <template #footer>
          <ElButton v-if="actionType !== 'detail'" type="primary"  @click="addCoupon">
            {{ t('exampleDemo.save') }}
          </ElButton>
          <ElButton @click="CouponDialog = false">{{ t('dialogDemo.close') }}</ElButton>
        </template>
      </Dialog>
</ContentWrap>
</template>